﻿using System;
using System.Collections.Generic;
using System.Text;
using Eqwww.Domain.Models.QuartzJob;
using Eqwww.Code;
using Eqwww.Data;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Eqwww.Domain;

namespace Eqwww.QuartzJob.Application
{
    public class DefaultScheduleApp : IScheduleApp
    {
        private ApplicationDbContext _context;
        private IModelHandler _modelHandler;
        public DefaultScheduleApp(ApplicationDbContext context, IModelHandler modelHandler)
        {
            _context = context;
            _modelHandler = modelHandler;
        }
        public List<ScheduleModel> FindList(Pagination pagination)
        {
            var expression = ExtLinq.True<ScheduleModel>();
            expression = expression.And(x => x.DeleteMark != true);
            var data = _context.FindQueryable(expression, pagination);
            data = data.AsNoTracking().Include(x => x.CreateUser).Include(x => x.LastUpdateUser).Include(x => x.DeleteUser);
            return data.ToList();
        }
        public ModelResult Create(ScheduleModel model, ScheduleLogModel logModel)
        {
            _modelHandler.Create(model);
            _context.Add(model);
            logModel.ScheduleId = model.Id;
            _context.Add(logModel);
            _context.SaveChanges();
            return Common.SuccessResult();
        }
        public ScheduleModel Get(string id)
        {
            var model = _context.Set<ScheduleModel>()
                .Include(x=>x.CreateUser)
                .Include(x=>x.LastUpdateUser)
                .Include(x=>x.DeleteUser)
                .AsNoTracking().FirstOrDefault(x => x.Id == id);
            return model;
        }
        public ModelResult Update(ScheduleModel model, ScheduleLogModel logModel)
        {
            _modelHandler.Update(model);
            _context.Update(model);
            _context.Add(logModel);
            _context.SaveChanges();
            return Common.SuccessResult();
        }
        public ModelResult Delete(ScheduleModel model, ScheduleLogModel logModel)
        {
            _modelHandler.Delete(model);
            _context.Update(model);
            _context.Add(logModel);
            _context.SaveChanges();
            return Common.SuccessResult();
        }
        public IList<ScheduleLogModel> FindLogList(Pagination pagination, string scheduleId)
        {
            var expression = ExtLinq.True<ScheduleLogModel>();
            if (!string.IsNullOrEmpty(scheduleId))
                expression = expression.And(x => x.ScheduleId == scheduleId);
            return _context.FindList(expression, pagination);
        }
    }
}
